package P150;

import java.util.HashMap;
import java.util.Map;

public class P56 {

    class Node {
        int val;
        Node next;
        Node random;

        public Node(int val) {
            this.val = val;
            this.next = null;
            this.random = null;
        }
    }

    public Node copyRandomList(Node head) {
        Map<Node, Node> cache = new HashMap<>();
        copyRandomList(head, cache);
        return cache.get(head);
    }

    public Node copyRandomList(Node head, Map<Node, Node> cache) {
        if (head == null) {
            return null;
        }
        while (!cache.containsKey(head)) {
            Node newHead = new Node(head.val);
            cache.put(head, newHead);
            newHead.next = copyRandomList(head.next, cache);
            newHead.random = copyRandomList(head.random, cache);
        }
        return cache.get(head);
    }
}
